<?php
class Common {
	
	public function __construct(){
		
	}
	
	function urlParser($arrReplace, $sString){
		
		$arrSplit	=	explode("([a-zA-Z0-9-_]+)",$sString);
		$iCount		=	count($arrSplit);
        
		$sNewString	='';
		
		for($i=0; $i<$iCount; $i++){
			if(	
                !isset ($arrSplit[$i]) ||
                !isset ($arrReplace[$i])
               ){ 
				//self::checkNullIndex($arrSplit, $i)=='' || 
				//self::checkNullIndex($arrReplace, $i)=='') {
				   // var_dump(self::checkNullIndex($arrSplit, 0), self::checkNullIndex($arrReplace, 0));die;
				 continue;   
				}
				
			$sNewString	.=	$arrSplit[$i].$arrReplace[$i];
		}
		return $sNewString;
		
	}
	
	
/*	private function getSplitURL($arg2, $arrSplitStr, &$arrAlias){
		$key=$nextKey='';
		
   		if(!is_null($arrSplitStr[0])){
	    	$hashPattern=explode($arrSplitStr[0],$arg2);
	   		$arrAlias[]=$hashPattern[0];
	   		$key=$arrSplitStr[0]; 
   			$nextKey=isset($hashPattern[1])?$hashPattern[1]:'';
   			
   		}else {
   			$arrAlias[]=$arg2;
   		}
   		
   		if(self::checkNullIndex($hashPattern,1)!='' AND self::checkNullIndex($arrSplitStr,1)!=''){
	    	$hashPattern=explode($arrSplitStr[1],$hashPattern[1]);
	   		$arrAlias[]=$hashPattern[0];
	   		$key=$arrSplitStr[1];
   			$nextKey=isset($hashPattern[1])?$hashPattern[1]:'';
   				
   		}else if($nextKey!=''){
   			$arrAlias[]=$nextKey;
   			$nextKey ='';
   		}
   		if(self::checkNullIndex($hashPattern,2)!='' AND self::checkNullIndex($arrSplitStr,2)!=''){
	    	$hashPattern=explode($arrSplitStr[2],$hashPattern[2]);
	   		$arrAlias[]=$hashPattern[0];
	   		$key=$arrSplitStr[2];
	   		
   		}else if($nextKey!=''){
   			$arrAlias[]=$nextKey;
   			
   		}
   		
   		$arrAlias[]=str_replace('-','',$key);
   		   		
   		return $arrAlias;
	}
*/	
/*	private function detectPage($argURL){
		$arrURL_key=Zend_Registry::get('arrURL_key');
		$arrListKey=$arrURL_key['list_key'];
		foreach ($arrListKey as $val) {
	     	if(strpos($argURL,$val)!==false){
	     		
	     		return $val;
	     	}
		}
		return $arrListKey[0];
	}
*/	/**
	 * Get param from rewrited url
	 *
	 * @return array
	 */
	/*public function getParamRewrite(){ 
    	$arg1=Zend_Controller_Action::getRequest()->arg1;
    	$arg2=Zend_Controller_Action::getRequest()->arg2;
		$arrURL_key=Zend_Registry::get('arrURL_key');
    	
		$url_type=array();
     	$arg1_alias=$arg2_alias='';
     	
     	if(strpos($arg1,$arrURL_key['by_city'])!==false){
     		$url_type['key']='by_city';
     	}
		elseif(strpos($arg1,$arrURL_key['by_register'])!==false){
     		$url_type['key'] = 'by_register';
     		
     	}
     	$key_1 = $arrURL_key[$url_type['key']];
     	
     	$arrAlias=array();
     	$arrAlias[]=$url_type['key'];
     	
    	if(strpos($arg1, $key_1)!==false){
	    	$hashPattern=explode($key_1,$arg1);
	    	if(count($hashPattern)>0){
	    		$arrAlias[]=$hashPattern[1];
	    	}    	
    	}
     	if(!is_null($arg2)){
     		$k=self::detectPage($arg2);
			$arrSplitStr=$arrURL_key[$url_type['key'].'_'.$k];
     		$arrAlias=self::getSplitURL($arg2,$arrSplitStr,$arrAlias);
     		
     	}
		if(strpos($url_type['key'],'by_star')!==false){
			$arrAlias [1] = intval($arrAlias[1]);
		}
     	
		return $arrAlias;
	}*/
	public function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
          /*
          $interval can be:
          yyyy - Number of full years
          q - Number of full quarters
          m - Number of full months
          y - Difference between day numbers
          (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
          d - Number of full days
          w - Number of full weekdays
          ww - Number of full weeks
          h - Number of full hours
          n - Number of full minutes
          s - Number of full seconds (default)
          */

          if (!$using_timestamps) {
          $datefrom = strtotime($datefrom, 0);
          $dateto = strtotime($dateto, 0);
          }
          $difference = $dateto - $datefrom; // Difference in seconds
        
          switch($interval) {
        
          case 'yyyy': // Number of full years
        
              $years_difference = floor($difference / 31536000);
              if (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom), date("j", $datefrom), date("Y", $datefrom)+$years_difference) > $dateto) {
              $years_difference--;
              }
              if (mktime(date("H", $dateto), date("i", $dateto), date("s", $dateto), date("n", $dateto), date("j", $dateto), date("Y", $dateto)-($years_difference+1)) > $datefrom) {
              $years_difference++;
              }
              $datediff = $years_difference;
              break;
        
          case "q": // Number of full quarters
        
              $quarters_difference = floor($difference / 8035200);
              while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($quarters_difference*3), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
              $months_difference++;
              }
              $quarters_difference--;
              $datediff = $quarters_difference;
              break;
        
          case "m": // Number of full months
        
              $months_difference = floor($difference / 2678400);
              while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
              $months_difference++;
              }
              $months_difference--;
              $datediff = $months_difference;
              break;
        
          case 'y': // Difference between day numbers
        
              $datediff = date("z", $dateto) - date("z", $datefrom);
              break;
        
          case "d": // Number of full days
        
              $datediff = floor($difference / 86400);
              break;
        
          case "w": // Number of full weekdays
        
              $days_difference = floor($difference / 86400);
              $weeks_difference = floor($days_difference / 7); // Complete weeks
              $first_day = date("w", $datefrom);
              $days_remainder = floor($days_difference % 7);
              $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
              if ($odd_days > 7) { // Sunday
              $days_remainder--;
              }
              if ($odd_days > 6) { // Saturday
              $days_remainder--;
              }
              $datediff = ($weeks_difference * 5) + $days_remainder;
              break;
        
          case "ww": // Number of full weeks
        
              $datediff = floor($difference / 604800);
              break;
        
          case "h": // Number of full hours
        
              $datediff = floor($difference / 3600);
              break;
        
          case "n": // Number of full minutes
        
              $datediff = floor($difference / 60);
              break;
        
          default: // Number of full seconds (default)
        
            $datediff = $difference;
          break;
          }
        
          return $datediff;

  }
	
	/**
	 * Get value of array, at index location
	 *
	 * @param array $arr
	 * @param index $ind
	 * @param string $key
	 * @return string
	 */
	public function getArrayVal($arr, $ind, $key=''){ 
		if(isset($arr[$ind])) {
			return $arr[$ind][$key];
		}
		return '';
	}
	/**
	 * Prevent access to unexist index
	 *
	 * @param array $arr
	 * @param integer $ind
	 * @return string
	 */
	public function checkNullIndex($arr, $ind){
		if(isset($arr[$ind])) {
			return $arr[$ind];
		}
		return '';
	}
	
	
	public function removeNull($text, $key='Not Completed'){
		$arrLang=Zend_Registry::get('translator');
		
		if(empty($text) OR is_null($text) OR trim($text)==''){
			return $arrLang->_($key);
		}
		return $text;
	}
	
	public function callImage($path, $no_image='no_img.png'){
		if(empty($path) OR is_null($path) OR trim($path)==''){
			return $no_image;
		}
		return $path;
	}
	
	static function subString($text, $maxLength = 15, $dot = "..."){
		$words = preg_split('/\s/', $text); 
		$count=count($words);
		if($count<=$maxLength) {
			$result=$text;
		}else{
			$result='';
			for ($i=0; $i<$maxLength; $i++){
				$result.=$words[$i].' ';
			}
		}
		return $result.$dot;
	}
	public function check_input($string,$form){ 
		$result = '
			<script language="javascript">
			function validate_'.$form.'(){
		';
		$element_array = explode(",",str_replace(" ","",trim($string)));
		foreach ($element_array as $element)
		{
			$element=trim($element);
			$item = 'document.'.$form.'.'.$element;
			if(strpos($element, "email")===false){
				$result .= '
					if ('.$item.'.value == "")
						{	
							alert("Bắt buộc phải nhập, vui lòng kiểm tra lại!");
							'.$item.'.focus();
							return false;}';
			} else {
				$result.='
					if (('.$item.'.value.indexOf(\'@\') <=0) || (('.$item.'.value.charAt('.$item.'.value.length-4) != \'.\') && ('.$item.'.value.charAt('.$item.'.value.length-3) != \'.\')))
											{
												alert("Định dạng email không đúng, vui lòng nhập lại!");
												'.$item.'.focus();			
												return false;}';
			}
			
		}
		$result .= '
			return true;
			}
			</script>';
		return $result;
		/*if ( !document.form1.email_address.value.match( /^[a-zA-Z]+$/ ) )  ) {
	    alert ( "Please enter letters only." );
	    return false;
	  } else { */
	}

	public function message($string,$name){
		$result = '
			<script language="javascript">
			message_'.$name.'()
			function message_'.$name.'(){
		';
		$result.='alert("'.$string.'");';
		$result.='}</script>';
		return $result;
	}
	public function check_email($email) {
		return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
	}
	public function check_username($username) {
		return preg_match('/^[a-z0-9_]+$/',$username);
		
	}
    function date($data,  $format='d-m-Y'){    
      if (preg_match ("/^([0-9]{1,2})-([0-9]{1,2})-([0-9]{4})$/", $data, $parts))
      {
        //check weather the date is valid of not

    	if(checkdate($parts[2],$parts[1],$parts[3]))
        //$data=strtotime($data);
    	   return true;  
      }
      return false;
    }
	/**
	 * Get List of array by $key
	 *
	 * @param array $array	
	 * @param string $key
	 * @return string $strLic
	 */
	public  function getListFromArray($array,$key,$is_array=0) {
		$count_array = count($array);
		$strLic=$comma3='';
		for ($i = 0; $i < $count_array; $i++) {
			$strLic .=$comma3.$array[$i][$key];			
			$comma3=',';
		}
		if($is_array!=0)
		$strLic=split(",",$strLic);
		return $strLic;
	}
	/**
	 * Change key of array 
	 *
	 * @param array $array	
	 * @param string $key1
	 * @param string $key1
	 * @return array $strLic
	 */
	public  function changeKeyArray($array, $key1, $key2='', $key3='') {
		$count_array = count($array);
		$newArr=Array();
		for ($i = 0; $i < $count_array; $i++) {
			$newKey=$array[$i][$key1];
			# combine two 2 key 
			if($key2!='') $newKey.='.'.$array[$i][$key2];
			if($key3!='') $newKey.='.'.$array[$i][$key3];
			$newArr[$newKey] = $array[$i];			
		}
		unset($count_array);
		unset($array); unset($key1); unset($key2);
		
		return $newArr;
	}

	public  function changeArray($array, $key,$bList=false) {
		$count_array = count($array);
		$newArr=Array();
		for ($i = 0; $i < $count_array; $i++) {
			$newArr[] = $array[$i][$key];			
		}
		if($bList){
			if(count($newArr)>0){
				$newArr=array_unique($newArr);
				$strLic=implode(',', $newArr);
			} else {
				$strLic='-1';
			}
			return $strLic;
		} else {
			return $newArr;
		}
		unset($count_array);
		unset($array); unset($key);
	}
	/**
	 * get order by 
	 *	 
	 * @return String $strLic
	 */
	public function getOrderBY($order='',$sort='', $offset=0, $size='all') {
		$SQL='';
        $order = trim($order);
		if($order) {
		      
			$SQL .= " ORDER BY ".$order;
		}
		if(trim($sort)) {
			$SQL.=" ".$sort;
		}
		if($size!='all') {
			$SQL.=" LIMIT $offset, $size";
		}
		return $SQL;
	}
	/**
	 * get param type int 
	 * @param $request,$nameparam=''
	 * @return int 
	 */
	public  function getInt($request,$nameparam='') {		
		return intval(Zend_Controller_Action::getRequest()->$nameparam);
	}
	/**
	 * get param type String 
	 * @param $request,$nameparam=''
	 * @return String 
	 */
	public  function getString($request,$nameparam='',$tab='') {
			
		return  htmlspecialchars(strip_tags(Zend_Controller_Action::getRequest()->$nameparam,$tab));
	}
	/**
	 * get paging 
	 * @param $request,$data='',$limit=20,$nameparam='page'
	 * @return $paginator 
	 */
/*	public  function getPaging_bk($request,$data='',$limit=20,$nameparam='page') {		
		Zend_View_Helper_PaginationControl::setDefaultViewPartial('main/paging.phtml');
		$paginator = Zend_Paginator::factory($data);
		$paginator->setItemCountPerPage($limit);
		$paginator->setCurrentPageNumber($request->getParam($nameparam,1));
		return $paginator;
	}*/
	public function getRandomByArray($arr=''){
		$arrOut=Array();
		if($arr!=''){
			$iCount=count($arr);
			for($i=0;$i<$iCount;$i++){
				for($j=0;$j<=$i;$j++){
					$arrOut[]=$arr[$i];
				}
			}
			$ran=rand(0,(count($arrOut)-1));
			//var_dump($arrOut);
			return $arrOut[$ran];
		}
	}
	function convertnovn($string, $length = 100, $strSymbol='-', $isToLower = 1)
	 {
	  $arrCharFrom= array(
	       "ạ","á","à","ả","ã","Ạ","Á","À","Ả","Ã",
	       "â","ậ","ấ","ầ","ẩ","ẫ","Â","Ậ","Ấ","Ầ","Ẩ","Ẫ",
	       "ă","ặ","ắ","ằ","ẳ","ẫ","Ă","Ắ","Ằ","Ẳ","Ẵ","Ặ",
	       "ê","ẹ","é","è","ẻ","ẽ","Ê","Ẹ","É","È","Ẻ","Ẽ",
	       "ế","ề","ể","ễ","ệ","Ế","Ề","Ể","Ễ","Ệ",
	       "ọ","ộ","ổ","ỗ","ố","ồ","Ọ","Ộ","Ổ","Ỗ","Ố","Ồ","Ô","ô",
	       "ó","ò","ỏ","õ","Ó","Ò","Ỏ","Õ",
	       "ơ","ợ","ớ","ờ","ở","ỡ",
	       "Ơ","Ợ","Ớ","Ờ","Ở","Ỡ",
	       "ụ","ư","ứ","ừ","ử","ữ","ự","Ụ","Ư","Ứ","Ừ","Ử","Ữ","Ự",
	       "ú","ù","ủ","ũ","Ú","Ù","Ủ","Ũ",
	       "ị","í","ì","ỉ","ĩ","Ị","Í","Ì","Ỉ","Ĩ",
	       "ỵ","ý","ỳ","ỷ","ỹ","Ỵ","Ý","Ỳ","Ỷ","Ỹ",
	       "đ","Đ"
	       );
	    $arrCharEndNoVn= array(
	    "a","a","a","a","a","A","A","A","A","A",
	    "a","a","a","a","a","a","A","A","A","A","A","A",
	    "a","a","a","a","a","a","A","A","A","A","A","A",
	    "e","e","e","e","e","e","E","E","E","E","E","E",
	    "e","e","e","e","e","E","E","E","E","E",
	    "o","o","o","o","o","o","O","O","O","O","O","O","O","o",
	    "o","o","o","o","O","O","O","O",
	    "o","o","o","o","o","o",
	    "O","O","O","O","O","O",
	    "u","u","u","u","u","u","u","U","U","U","U","U","U","U",
	    "u","u","u","u","U","U","U","U",
	    "i","i","i","i","i","I","I","I","I","I",
	    "y","y","y","y","y","Y","Y","Y","Y","Y",
	    "d","D"
	    );
	  $arrCharFilter = str_replace($arrCharFrom,$arrCharEndNoVn,trim($string));
	  if (mb_strlen($arrCharFilter,"UTF-8") > $length) {
	   $arrCharFilter = mb_substr($arrCharFilter, 0, $length,"UTF-8");
	  }
	  $arrCharFilter = preg_replace('/[\W|_]+/',$strSymbol,$arrCharFilter);
	  return $isToLower ? strtolower($arrCharFilter) : $arrCharFilter;
	 }
	 function truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
	{
	    if ($length == 0)
	        return '';
	
	    if (is_callable('mb_strlen')) {
	        if (mb_detect_encoding($string, 'UTF-8, ISO-8859-1') === 'UTF-8') {
	            // $string has utf-8 encoding
	            if (mb_strlen($string) > $length) {
	                $length -= min($length, mb_strlen($etc));
	                if (!$break_words && !$middle) {
	                    $string = preg_replace('/\s+?(\S+)?$/u', '', mb_substr($string, 0, $length + 1));
	                }
	                if (!$middle) {
	                    return mb_substr($string, 0, $length) . $etc;
	                } else {
	                    return mb_substr($string, 0, $length / 2) . $etc . mb_substr($string, - $length / 2);
	                }
	            } else {
	                return $string;
	            }
	        }
	    }
	    // $string has no utf-8 encoding
	    if (strlen($string) > $length) {
	        $length -= min($length, strlen($etc));
	        if (!$break_words && !$middle) {
	            $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
	        }
	        if (!$middle) {
	            return substr($string, 0, $length) . $etc;
	        } else {
	            return substr($string, 0, $length / 2) . $etc . substr($string, - $length / 2);
	        }
	    } else {
	        return $string;
	    }
	}
/*	function convert($str,$lang1, $lang2){
		$en = array(
                'search',
                'ranking-by'
	            );
		$fr = array(
                'rechercher',
                'classement'
	            ); 
		$vi = array (
                 'tim-kiem',
                'xep-hang-resort'
			);
		if ($lang1===$lang2 && !$this->NEW_URL) return $str;
        $uri = explode('/', $str);    
		$return = '/'.str_replace($$lang1, $$lang2, $uri[1]);
        if (self::checkNullIndex($uri, 2)){        
            $array1 = array_slice( $$lang1, 7, 17);
            $array2 = array_slice( $$lang2, 7, 17);
            $return .= '/'.str_replace($array1, $array2, $uri[2]);
        }
		return $return;
	}*/
	function sqlSearch($keyword, $sField) {
	   if ($keyword=='') return '';
	   $keyword=addslashes($keyword);
       $keyword = preg_replace('/\s\s+/', '%', $keyword);
       $keyword = str_replace(' ', '%', $keyword);
       $like_cond = " and $sField like '%$keyword%'";
       
	   return $like_cond;
	}
}
?>